#!/usr/bin/env node

let axios = require('axios')
let inquirer = require('inquirer')
let chalk = require('chalk')

let time = 1000,
    getListUrl = 'https://bifen4m.qiumibao.com/json/list.htm'

main(getListUrl, time)
/**
 * 主要流程，入口函数
 * 1 获取赛事列表
 * 2 筛选赛事
 * 3 判断是否有直播赛事，进而显示选项或者退出
 * 4 若有直播赛事，则更加用户选择的赛事去定时获取赛事文本信息
 * @param {String} getListUrl 
 * @param {Number} time 
 */
async function main(getListUrl, time) {

    let getListRes = await axios(getListUrl),
        allMatchs = getListRes.data.list,
        liveMatchlist = allMatchs.filter(liveMatchs)

    if (!isExit(liveMatchlist.length, '暂时没有可观看的直播赛事！')) {
        let matchId = await showChoices(liveMatchlist).matchId
        await getLiveMatchText(matchId, time)
    }

}

/**
 * 把赛事 items 转换为选项 choices
 * @param {Array} items 
 * @return {Array} choices
 */
function items2choices(items) {
    let choices = []
    for (let item of items) {
        choices.push({
            name: `${item.home_team} VS ${item.visit_team}`,
            value: item.id
        })
    }
    return choices
}

/**
 * 用于筛选赛事的函数
 * @param {Object} item
 * @return {Boolean}
 */
function liveMatchs(item) {
    let pattern = /[a-z]{1,}\.live/
     if (item.period_cn !== '完赛' && item.period_cn && pattern.test(item.from))
        return true
}
/**
 * 判断是否有符合的直播赛事，是否退出
 * @param {Number} length 
 * @param {String} message 
 * @return {Boolean}
 */
function isExit(length, message) {
    if (length === 0) {
        console.log(message)
        return true
    }
}

/**
 * 显示出赛事选项
 * @param {Array} items 
 * @param {Object} config 
 * @return {Promise}
 */
function showChoices(items,
    config = {
        type: 'list',
        name: 'matchId',
        message: '请选择想观看的赛事：',
        pageSize: 12,
        choices: items2choices(items)
    }) {
    inquirer.prompt([config])
}
/**
 * 定时获取直播赛事文本
 * @param {Number} matchId 
 * @param {Number} time
 */
function getLiveMatchText(matchId, time) {
    let TextId = -1

    console.log('正在获取比赛信息...')
    console.log()

    setInterval(_ => {
        axios(`https://dingshi4pc.qiumibao.com/livetext/data/cache/max_sid/${matchId}/0.htm`).then(res => {
            if (TextId !== res.data) {
                TextId = res.data
                axios(`https://dingshi4pc.qiumibao.com/livetext/data/cache/livetext/${matchId}/0/lit_page_2/${TextId}.htm`)
                    .then(res => {
                        for (let list of res.data) {
                            console.log(`当前时间：${chalk.blue(list.pid_text)}  当前比分：${chalk.green(list.home_score)}:${chalk.green(list.visit_score)}`)
                            console.log(`${list.user_chn}：${list.live_text}`)
                            console.log()
                        }
                    }).catch(err => {})
            }
        }).catch(err => {})
    }, time)
}